<template>
    <div class="sync-form-container" v-loading="loading" element-loading-text="">
        <div class="sync-form">
            <div class="sync-item">
                <h5>执行动作</h5>
                <div class="actions">
                    <div class="action-item" @click="handleSelectAction('NAME')"
                         :class="{ 'active': tab === 'NAME' }">
                        <el-inpu v-model="form.name" placeholder="接口名称"></el-inpu>
                        <el-inpu v-model="form.remark" placeholder="接口描述"></el-inpu>
                    </div>
                    <div class="action-item" @click="handleSelectAction('SCRIPT')"
                         :class="{ 'active': tab === 'SCRIPT' }">
                        <h6>函数定义</h6>
                    </div>
                    <div class="action-item" @click="handleSelectAction('INPARAM')"
                         :class="{ 'active': tab === 'INPARAM' }">
                        <h6>函数入参</h6>
                    </div>
                    <div class="action-item" @click="handleSelectAction('OUTPARAM')"
                         :class="{ 'active': tab === 'OUTPARAM' }">
                        <h6>函数出参</h6>
<!--
                        <p>目标表单中查询数据修改，无则新增</p>
-->
                    </div>
                </div>
            </div>
            <div v-if="tab === 'SCRIPT'" class="svc-target">
                <div class="sync-item lc-code-wrap">
                    <h5>服务器脚本</h5>
                    <div class="lc-code">
                        <codemirror v-model="form.script" :options="cmOptions"></codemirror>
                    </div>
                </div>
            </div>
            <div v-if="tab === 'INPARAM'" class="svc-target">
                <div class="sync-item lc-code-wrap">
                    <h5>服务器脚本</h5>
                    <div class="lc-code">
                        <s-json-schema-editor :schema.sync="form.inparam_schema" :show-default-value="true" :is-mock="false" :show-raw="true"
                                              @schema-change="handleSchemaChange"></s-json-schema-editor>
                    </div>
                </div>
            </div>
            <div v-if="tab === 'OUTPARAM'" class="svc-target">
                <div class="sync-item lc-code-wrap">
                    <h5>服务器脚本</h5>
                    <div class="lc-code">
                        <s-json-schema-editor :schema.sync="form.outparam_schema" :show-default-value="true" :is-mock="false" :show-raw="true"
                                              @schema-change="handleSchemaChange"></s-json-schema-editor>                    </div>
                </div>
            </div>
        </div>
        <div class="demo-drawer__footer clear">
            <el-button type="primary" @click="ok()">确 定</el-button>
            <el-button @click="cancel()">取 消</el-button>
        </div>
    </div>
</template>
<script>
import { createEmptyFlow, isBeginNode } from '@/utils/wf-utils';
import { mapState, mapActions } from 'vuex';
import CODE_TYPE_DFT from './code-type-dft';

let DFT = {
    stlc_code: '',
    name: '',
    remark: '',
    scope_type: 3,
    form_id: null,
    view_id: null,
    flow_id: null,
    node_id: null,
    cron: null,
    trigger_type: 0,        // 0-自动（流程/定时任务默认），1-数据生效，2-数据删除/失效，3-流程提交
    target_form_id: null,
    action_type: 'INSERT',  // INSERT / UPDATAE / DELETE / UPSERT / SCRIPT
    syncmap: {},
    syncfilter: {},
    status: 1,
    script: ''
};

export default {
    name: 'LowcodeRobot',
    // props: [ 'form' ],
    props: {
        saveMode: {
            type: String,
            default: 'save'     // save - 保存， temp - 返回json
        },
        robotId: [ String, Number ],
        robot: [ Object ],
        type: {
            type: String,
            default: 'TASK'
        },
        formId: [ String, Number ],
        viewId: [ String, Number ],
        flowId: [ String, Number ],
        nodeId: [ String, Number ]
    },
	components: {

    },
	data() {
        let self = this;
		return {
		    form: _.cloneDeep(DFT),
            origForm: null,     // 原始表单/流程表单
            loading: false,

            error: null,
            tab: 'NAME',
            cmOptions: {
                // codemirror options
                tabSize: 4,
                mode: 'text/javascript',
                theme: 'darcula',
                lineNumbers: true,
                line: true,
                indentWithTabs: true,
                smartIndent: false,
                extraKeys: {
                    "Ctrl-S": (editor) => {
                        // console.log(a, b, c);
                        // self.save();
                    },
                    "Tab": (cm) => {
                        if (cm.somethingSelected()) {
                            cm.indentSelection('add');
                        } else {
                            cm.replaceSelection(
                                cm.getOption ? "\t" : Array(cm.getOption("indentUnit") + 1).join(" "),
                                "end",
                                "+input");
                        }
                    }
                },
            },
		};
	},
	created() {

	},
    mounted() {
        // this.form.form_id = _.get(this.form, 'form_id');
        this.init();
    },
    computed: {
        isFlowForm() {
            return this.origForm && this.origForm.use_type === 'WORKFLOW';
        },
        /*hasTj() {
            let details = this.currentInfo.details;
            let idx = _.findIndex(details, { type: 2 });
            return details && details.length && idx >= 0;
        }*/
    },
    filters: {
        triggerTypeLabel(type) {
            if(type === 1) {
                return "数据生效时";
            } else if(type === 2) {
                return "数据删除时";
            } else if(type === 3) {
                return "流程提交时";
            } else {
                return "";
            }
        },
        actionTypeLabel(type) {
            if(type === 'INSERT') {
                return "新增数据"
            } else if(type === 'UPDATE') {
                return "修改已有数据"
            } else if(type === 'DELETE') {
                return "删除已有数据"
            }
        }
    },
    watch: {
        type() {
            this.init();
        },
        formId() {
            this.init();
        },
        viewId() {
            this.init();
        },
        flowId() {
            this.init();
        },
        nodeId() {
            this.init();
        },
        robot: {
            deep: true,
            handle() {
                this.init();
            }
        },
        robotId() {
            this.init();
        },
        targetForm: {
            deep: true,
            handler(val) {
                if(val && val.form_id) {
                    this.form.targetForm = _.pick(val, [ 'form_id', 'form_name' ]);
                } else {
                    this.form.targetForm = val;
                }
                // this.form.targetForm = val;
            }
        }
    },
	methods: {
        emptyFn() {},
        errorTip(tip) {
            this.error = tip;
            this.loading = false;
        },
        async init() {
            this.error = null;
            this.loading = true;
            this.origForm = null;
            this.targetForm = {};

            // let tasks = await this.$japi.synctask.getFormSyncTasks(formId);

            let origForm = null;
            let targetForm = null;
            let form = null;
            let origFlow = null;

            // 修改
            if(this.robotId) {
                form = await this.$japi.synclowcode.getSyncLowcode(this.robotId);

                if(!form) {
                    return this.errorTip('修改数据不存在！');
                }
            } else if(this.robot && this.robot.stlc_code) {
                form = _.cloneDeep(this.robot);
            } else {    // 新增
                form = _.cloneDeep(DFT);

                if(this.type === 'FORMTASK') {
                    if(!this.formId) {
                        return this.errorTip('输入参数不正确！');
                    }
                    form.trigger_type = 1;
                } else if(this.type === 'FLOWTASK' || this.type === 'TASK') {
                    /*if(!this.nodeId || !this.flowId) {
                        this.error = '输入参数不正确！';
                        return;
                    }*/
                } else if(this.type === 'CRON') {

                } else {
                    return this.errorTip('输入参数不正确！');
                }

                form.stlc_code = this.$utils.getNanoid();
                form.type = this.type;
                form.form_id = this.formId;
                form.view_id = this.viewId;
                form.flow_id = this.flowId;
                form.node_id = this.nodeId;
            }

            if(this.type === 'FLOWTASK' || this.type === 'TASK') {
                if(form.flow_id) {
                    origFlow = await this.$japi.flow.getFlow(form.flow_id);

                    let flowFormId = _.get(origFlow, 'form_id');

                    if(!form.form_id) {
                        form.form_id = flowFormId;
                    }
                }

            } else if(form.type === 'FORMTASK') {

            } else  if(this.type === 'CRON') {

            } else {
                return this.errorTip('输入参数不正确！');
            }

            if(form.form_id) {
                origForm = await this.$japi.form.getFormById(form.form_id);
            }

            if(form.target_form_id) {
                targetForm = await this.$japi.form.getFormById(form.target_form_id);
                if(targetForm) this.targetForm = targetForm;
            }

            if(!form.script) {
                form.script = CODE_TYPE_DFT[ 'serverJs' ];
            }

            this.form = form;
            this.origForm = origForm;
            this.origFlow = origFlow;
            this.loading = false;
        },
        async handleShowFormSelectWin() {
            $WinForms({
                type: 'form',
                onSelect: async (info) => {
                    let form = _.get(info, 'form');
                    // let view = _.get(info, 'view');

                    if(!form || !form.form_code) return;

                    let formId = _.get(form, 'form_id');
                    let formInfo = await this.$japi.form.getFormById(formId);
                    this.targetForm = formInfo;
                    this.form.target_form_id = _.get(formInfo, 'form_id');
                }
            });
        },
        handleSelectTriggerType(type) {
            this.form.trigger_type = type;
        },
        handleSelectAction(type) {
            this.form.action_type = type;
        },
        handleShowExeLog() {
            this.$message('开发中，敬请期待。');
        },
        cancel() {
            this.$emit("close");
        },
        async ok() {
            // this.form.form_id = _.get(this.form, 'form_id');
            let form = _.cloneDeep(this.form);
            let ret = null;

            if(this.saveMode === 'temp') {
                this.$emit('save', form);
            } else {
                this.loading = true;

                if(form.stlc_id) {
                    ret = await this.$japi.synclowcode.updateSyncLowcode(form);
                } else {
                    ret = await this.$japi.synclowcode.createSyncLowcode(form);
                }

                if(ret) {
                    // this.robotId = _.get(this.form, 'stlc_id');
                    // this.init();

                    this.$emit('save', form);
                }

                this.loading = false;
            }
        }
	}
};
</script>
<style scoped lang="scss">
    .el-button.fixed-width {
        width: 120px;
    }
    .sync-form-container {
        display: flex;
        flex-flow: column;
        height: 100%;
    }
    .sync-form {
        border-top: 1px solid #F2F2F2;
        flex: 1;
        overflow-y: auto;
        /*padding-bottom: 20px;*/
        padding: 0 10px;
        display: flex;
    }

    p {
        line-height: 1.5;
        font-size: 12px;
        color: #999;

        &:last-child {
            margin-bottom: 0px;
            margin-top: 5px;
        }
    }

    .svc-target {
        display: flex;
        flex-flow: column;
        flex: 1;
    }

    .lc-code-wrap {
        flex: 1;
        margin-top: 0px;
        display: flex;
        flex-flow: column;

        .lc-code {
            flex: 1;
            height: 100%;
            overflow: auto;

            .vue-codemirror {
                height: 100%;
            }
        }
    }

    .sync-item {
        margin: 10px;

        h5 {
            margin: 10px 0;
            font-weight: bold;
            display: flex;
            align-items: center;
        }

        .sync-hd {
            margin-bottom: 0px;
            font-weight: normal;
            margin-left: 10px;
        }

        .actions {
            display: flex;
            align-items: top;
            justify-content: flex-start;
            flex-flow: column;

            .action-item {
                width: 180px;
                min-height: 82px;
                border: 1px solid #DDD;
                border-radius: 5px;
                /*margin-right: 10px;*/
                margin-bottom: 10px;
                padding: 10px;
                cursor: pointer;

                h6 {
                    font-size: 16px;
                    margin: 0px;
                    font-weight: normal;
                }

                &:hover, &.active {
                    border-color: #3a8ee6;
                    background: #ecf5ff;

                    h6 {
                        color: #3a8ee6;
                    }
                }
                &:last-child {
                    margin-right: 0px;
                }
            }
        }
    }
</style>
